package com.yinhe.music.yhmusic.pay;

import com.apkfuns.logutils.LogUtils;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.yinhe.music.yhmusic.base.BasePresenter;
import com.yinhe.music.yhmusic.base.IBaseModel;
import com.yinhe.music.yhmusic.constants.IConstants;
import com.yinhe.music.yhmusic.network.response.ResponseTransformer;
import com.yinhe.music.yhmusic.utils.Preferences;

public class PayPresenter extends BasePresenter<IBaseModel, PayContract.IPayView> implements PayContract.IPayPresenter {
    @Override
    public void getPayInfo(String payType, String productType, String product) {
        if (getView() == null) {
            return;
        }

        addSubscription(mModel.getPayInfo(payType, productType, product)
                .compose(ResponseTransformer.handleResult())
                .compose(schedulerProvider.applySchedulers())
                .subscribe(payInfo -> {
                    if (payType.equals(IConstants.WXPAY)) {
                        setWxPayInfo(payInfo);
                    } else {
                        setAliPayInfo(payInfo);
                    }
                }, throwable -> {
                    getView().showMessage(throwable);
                }));
    }

    @Override
    public void getPayResult(String orderNo) {
        if (getView() == null) {
            return;
        }

        addSubscription(mModel.getPayResult(orderNo)
                .compose(ResponseTransformer.handleResult())
                .compose(schedulerProvider.applySchedulers())
                .subscribe(payResultInfo -> {
                    getView().setPayResultUI(payResultInfo);
                }, throwable -> {
                    getView().showMessage(throwable);
                }));
    }

    private void setWxPayInfo(PayInfo payInfo) {
        PayReq request = new PayReq();
        request.appId = payInfo.getAppid();
        request.prepayId = payInfo.getPrepayid();
        request.partnerId = payInfo.getPartnerid();
        request.packageValue = payInfo.getPackagevalue();
        request.nonceStr = payInfo.getNoncestr();
        request.timeStamp = String.valueOf(payInfo.getTimestamp());
        request.sign = payInfo.getSign();
        Preferences.setOrderNo(payInfo.getOrderNo());
        LogUtils.d(request);
        getView().sendWechatPay(request);
    }

    private void setAliPayInfo(PayInfo payInfo) {
        getView().sendAliPay(payInfo.getPayUrl());
    }
}
